package cn.schoolwow.workflow.module.task.action.flow.complete.listener;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.workflow.domain.task.WorkFlowTaskResponse;
import cn.schoolwow.workflow.entity.WorkFlowDefinition;
import cn.schoolwow.workflow.entity.WorkFlowInstance;
import cn.schoolwow.workflow.entity.WorkFlowTask;
import cn.schoolwow.workflow.module.common.domain.QuickWorkFlowOption;

public class ExecuteBeforeCompleteTaskListenerFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        checkListenerExist(flowContext);
        executeListener(flowContext);
    }

    @Override
    public String name() {
        return "执行工作流任务完成之前事件";
    }

    private void checkListenerExist(FlowContext flowContext){
        QuickWorkFlowOption quickWorkFlowOption = flowContext.checkInstanceData(QuickWorkFlowOption.class);

        if(null==quickWorkFlowOption.workFlowTaskListener){
            flowContext.brokenCurrentFlow("工作流任务监听器不存在!");
        }
    }

    private void executeListener(FlowContext flowContext){
        QuickWorkFlowOption quickWorkFlowOption = flowContext.checkInstanceData(QuickWorkFlowOption.class);
        WorkFlowDefinition workFlowDefinition = flowContext.checkInstanceData(WorkFlowDefinition.class);
        WorkFlowInstance workFlowInstance = flowContext.checkInstanceData(WorkFlowInstance.class);
        WorkFlowTask workFlowTask = flowContext.checkInstanceData(WorkFlowTask.class);

        WorkFlowTaskResponse beforeWorkFlowTaskResponse = new WorkFlowTaskResponse();
        beforeWorkFlowTaskResponse.instanceId = workFlowInstance.getId();
        beforeWorkFlowTaskResponse.instanceStatus = workFlowInstance.getStatus();
        beforeWorkFlowTaskResponse.definitionId = workFlowInstance.getDefinitionId();
        beforeWorkFlowTaskResponse.definitionName = workFlowDefinition.getName();
        beforeWorkFlowTaskResponse.taskId = workFlowTask.getId();
        beforeWorkFlowTaskResponse.taskName = workFlowTask.getTaskName();
        beforeWorkFlowTaskResponse.contextData = workFlowInstance.getContextData();
        beforeWorkFlowTaskResponse.complete = false;

        quickWorkFlowOption.workFlowTaskListener.beforeTaskComplete(beforeWorkFlowTaskResponse);
        flowContext.putTemporaryData("beforeWorkFlowTaskResponse", beforeWorkFlowTaskResponse);
    }
}
